
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 89735
  Date: 2018/9/19
  Time: 11:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-1.12.4.min.js"></script>
    <%--引入bootstrap--%>
    <link href="${pageContext.request.contextPath}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="${pageContext.request.contextPath}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>

    <!-- 新增 -->
    <div class="modal fade" id="empAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="empName" class="col-sm-2 control-label">empName</label>
                            <div class="col-sm-10">
                                <input type="text" name="empName" class="form-control" id="empName" placeholder="empName">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="email" class="col-sm-2 control-label">email</label>
                            <div class="col-sm-10">
                                <input type="text" name="email" class="form-control" id="email" placeholder="Email" autocomplete="off">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">gender</label>
                            <div class="col-sm-10">
                                <div class="radio">
                                    <label class="radio-inline">
                                        <input type="radio" name="gender" id="gender_add_input" value="m" checked="checked"> 男
                                    </label>
                                    <label class="radio-inline">
                                        <input type="radio" name="gender" id="gender2_add_input" value="F"> 女
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">deptName</label>
                            <div class="col-sm-4">
                                <!-- 部门提交部门id即可 -->
                                <select class="form-control" name="dId" >
                                </select>
                            </div>
                        </div>
                    </form>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关 闭</button>
                    <button type="button" class="btn btn-primary" id="emp_save_btn" >保 存</button>
                </div>
            </div>
        </div>
    </div>
<%--搭建显示页面--%>
    <div class="container">
        <%--标题--%>
        <div class="row">
            <div class="col-md-12">
                <h1>SSM-CRUD</h1>
            </div>
        </div>
        <%--删除 新增按钮--%>
        <div class="row">
            <div class="col-md-4 col-md-offset-8">
                <button class="btn btn-primary" id="emp_add_modal_btn">新增</button>
                <button class="btn btn-danger">删除</button>
            </div>
        </div>
        <%--表格--%>
        <div class="row">
            <div class="col-md-12">
                <table class="table table-hover" id="emps_table">
                    <thead>
                        <tr>
                            <th>
                                <input type="checkbox" id="check_all"/>
                            </th>
                            <th>empID</th>
                            <th>empName</th>
                            <th>gender</th>
                            <th>email</th>
                            <th>deptName</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
        <%--分页--%>
        <div class="row">
            <div class="col-md-6" id="page_info_area"></div>
            <div class="col-md-6" id="page_nav_area"></div>
        </div>
    </div>

<%--<c:set var="aa" value="<script> alert('匡广腾')</script>"/>

<h2><%=Html.Encode(feedback.Message)%>${aa}</h2>
<input type="text" value="${aa}" id="aa">--%>
</body>
</html>

<script type="text/javascript">

    $(function () {
        getEmployee(1);
    });
    function getEmployee(pageNo) {
        $.ajax({
            url:"${pageContext.request.contextPath}/getemps",
            data:"pageNo="+pageNo,
            type:"GET",
            success:function(result){
                console.log(result);
                //1、解析并显示员工数据
                build_emps_table(result);
                //2、解析并显示分页信息
                build_page_info(result);
                //3、解析显示分页条数据
                build_page_nav(result);
            }
        });
    }



    function htmlEncodeJQ ( str ) {
        return $('<span/>').text( str ).html();
    }

    function htmlDecodeJQ ( str ) {
        return $('<span/>').html(str).text();
    }

    function build_emps_table(result){
        var emps=result.extend.pageInfo.list;
        //清空table表格
        $("#emps_table tbody").empty();
        $.each(emps,function(index,item) {
            console.log(index);
            var checkBoxTd = $("<td><input type='checkbox' class='check_item'/></td>");
            var empIdTd = $("<td></td>").append(item.empId);

            var empNameTd = $("<td></td>").text( item.empName );//.append(item.empName);
            var genderTd = $("<td></td>").append(item.gender=='M'?"男":"女");
            var emailTd = $("<td></td>").append(item.email);
            var deptNameTd = $("<td></td>").append(item.department.deptName);

            var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("编辑");
            editBtn.attr("edit-id",item.empId);

            var delBtn =  $("<button></button>").addClass("btn btn-danger btn-sm delete_btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
            delBtn.attr("del-id",item.empId);
            var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn);

            $("<tr></tr>").append(checkBoxTd)
                .append(empIdTd)
                .append(empNameTd)
                .append(genderTd)
                .append(emailTd)
                .append(deptNameTd)
                .append(btnTd)
                .appendTo("#emps_table tbody");


        });
    }
    function build_page_info(result) {
        $("#page_info_area").empty();
        $("#page_info_area").append("当前"+result.extend.pageInfo.pageNum+"页,总"+
            result.extend.pageInfo.pages+"页,总"+
            result.extend.pageInfo.total+"条记录");
        totalRecord = result.extend.pageInfo.total;
        currentPage = result.extend.pageInfo.pageNum;
    }
    //解析显示分页条，点击分页要能去下一页....
    function build_page_nav(result){
        //page_nav_area
        $("#page_nav_area").empty();
        var ul = $("<ul></ul>").addClass("pagination");

        //构建元素
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
        var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"));
        if(result.extend.pageInfo.hasPreviousPage == false){
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        }else{
            //为元素添加点击翻页的事件
            firstPageLi.click(function(){
                getEmployee(1);
            });
            prePageLi.click(function(){
                getEmployee(result.extend.pageInfo.pageNum -1);
            });
        }



        var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"));
        var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href","#"));
        if(result.extend.pageInfo.hasNextPage == false){
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        }else{
            nextPageLi.click(function(){
                getEmployee(result.extend.pageInfo.pageNum +1);
            });
            lastPageLi.click(function(){
                getEmployee(result.extend.pageInfo.pages);
            });
        }



        //添加首页和前一页 的提示
        ul.append(firstPageLi).append(prePageLi);
        //1,2，3遍历给ul中添加页码提示
        $.each(result.extend.pageInfo.navigatepageNums,function(index,item){

            var numLi = $("<li></li>").append($("<a></a>").append(item));
            if(result.extend.pageInfo.pageNum == item){
                numLi.addClass("active");
            }else{
                numLi.click(function(){
                    getEmployee(item);
                });
            }

            ul.append(numLi);
        });
        //添加下一页和末页 的提示
        ul.append(nextPageLi).append(lastPageLi);

        //把ul加入到nav
        var navEle = $("<nav></nav>").append(ul);
        navEle.appendTo("#page_nav_area");
    }


    //点击新增按钮弹出模态框。
    $("#emp_add_modal_btn").click(function(){
        //清除表单数据（表单完整重置（表单的数据，表单的样式））
        reset_form("#empAddModal form");

        //发送ajax请求，查出部门信息，显示在下拉列表中
            getDepts("#empAddModal select");
        //弹出模态框
        $("#empAddModal").modal({
            backdrop:"static"
        });
    });

    //清空表单样式及内容
    function reset_form(ele){
        $(ele)[0].reset();
        //清空表单样式
        $(ele).find("*").removeClass("has-error has-success");
        $(ele).find(".help-block").text("");
        $(ele).find("select").empty();
    }

    function getDepts() {
        $.ajax({
            url:"${pageContext.request.contextPath}/depts",
            type:"GET",
            success:function (result) {
                $.each(result.extend.depts,function (index,item) {
                    var optionEle=$("<option></option>").append(item.deptName).attr("value",item.deptId);
                    optionEle.appendTo("#empAddModal select")
                });


            }

        })

    }
    var empST;
    var verify=true;

    $("#empName").keyup(function () {
        clearTimeout(empST);
        empST=setTimeout(function (){
            var regName = /(^[\u4e00-\u9fa5]+$)|(^[a-zA-Z0-9]+[\s\.]?[a-z]+$)/;
            if(!regName.test($("#empName").val())){
                verify=false;
                show_validate_msg("#empName", "error", "用户名必须是2-5位中文或者6-16位英文和数字的组合");
                return false;
            }else{
                verify=true;
                show_validate_msg("#empName", "success", "");
            }

            var empName = $("#empName").val();
            $.ajax({
                url:"${pageContext.request.contextPath}/checkuser",
                data:"empName="+empName,
                type:"POST",
                success:function(result){
                    if(result.code==100){
                        show_validate_msg("#empName","success","");
                        $("#emp_save_btn").attr("ajax-va","success");
                        verify=true;
                    }else{
                        show_validate_msg("#empName","error",result.extend.va_msg);
                        $("#emp_save_btn").attr("ajax-va","error");
                        verify=false;
                    }
                }
            });
        },1500);


    });

    $("#email").keyup(function () {
        clearTimeout(empST);
        empST=setTimeout(function (){
            var regEmail = /^([a-z0-9]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
            if(!regEmail.test($("#email").val())){
                verify=false;
                show_validate_msg("#email", "error", "邮箱格式不正确");

            }else{
                verify=true;
                show_validate_msg("#email", "success", "");
            }
            console.log($("#email").val()+" "+verify);
        },1500);


    });
    $("#emp_save_btn").click(function () {
        console.log(verify);
        if(verify){
            $.ajax({
                url:"${pageContext.request.contextPath}/emp",
                type:"POST",
                data:$("#empAddModal form").serialize(),
                success:function(result){
                    //alert(result.msg);
                    if(result.code == 100){
                        //员工保存成功；
                        //1、关闭模态框

                        $("#empAddModal").modal('hide');

                        //2、来到最后一页，显示刚才保存的数据
                        //发送ajax请求显示最后一页数据to_page(totalRecord);
                    }else{
                        //显示失败信息
                        //console.log(result);
                        //有哪个字段的错误信息就显示哪个字段的；
                        if(result.extend.va_msg!=undefined){
                            show_validate_msg("#empName","error",result.extend.va_msg);
                        }
                        if(undefined != result.extend.errorFields.email){
                            //显示邮箱错误信息
                            show_validate_msg("#email", "error", result.extend.errorFields.email);
                        }
                        if(undefined != result.extend.errorFields.empName){
                            //显示员工名字的错误信息
                            show_validate_msg("#empName", "error", result.extend.errorFields.empName);
                        }
                    }
                }
            });
        }


    })


    function show_validate_msg(ele,status,msg){
        //清除当前元素的校验状态
        $(ele).parent().removeClass("has-success has-error");
        $(ele).next("span").text("");
        if("success"==status){
            $(ele).parent().addClass("has-success");
            $(ele).next("span").text(msg);
        }else if("error" == status){
            $(ele).parent().addClass("has-error");
            $(ele).next("span").text(msg);
        }
    }
</script>
